package com.itboye.sunsun.person.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.sunsun.MainHomeActivity;
import com.itboye.sunsun.MainHomeEnglishActivity;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.ConfigBean;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.controller.UnLoginState;
import com.itboye.sunsun.me.ui.SwitchLanguageObservable;
import com.itboye.sunsun.me.ui.SwitchLanguageObserver;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.utils.UIAlertView02;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsunhome.R;
import com.itboye.sunsunhome.util.Byalert;
import com.umeng.message.PushAgent;

import java.util.ArrayList;

public class SttingActivity extends BaseActivity implements OnClickListener {

    private TextView versionname, add_shap_title_tv;

    private RelativeLayout mylocationrelakefu, mylocationrelalanguage,
            protocalrela, aboutrela, mylocationrelaGeRen;
    private SwitchLanguageObservable obs;
    private SwitchLanguageObserver obser;

    // 退出登录
    private RelativeLayout exitrela;
    public static String EXITCHANGE = "com.itboye.sunsun.person.exit";

    private TextView tvtel;
    ImageView close_icon;
    String resultData;
    String uid;
    RelativeLayout re_version;
    private ArrayList<ConfigBean> arConfig;
    TextView hasNew;

    @Override
    @SuppressLint("InlinedApi")
    protected void onCreate(Bundle arg0) {
        // TODO Auto-generated method exitrela
        super.onCreate(arg0);
        setContentView(R.layout.activity_sttings);
        uid = (String) SPUtils.get(App.ctx, null,
                SPContants.USER_ID, "");
        if (uid == "" || uid == null) {
            exitrela.setVisibility(View.GONE);
        } else {
            exitrela.setVisibility(View.VISIBLE);
        }
        // 注册广播
        IntentFilter intentFilterAvart = new IntentFilter("sttringactivity");
        SttingActivity.this.registerReceiver(avartBroadcastReceiver,
                intentFilterAvart);
        insetINter();
        setStatusBarColor(R.color.home_blue);
        getVersionAvaliable();
    }

    int newVersion = 0;
    ConfigBean newConfigBean = null;

    public void getVersionAvaliable() {

        MyJsonRequest.Builder<ArrayList<ConfigBean>> builder = new MyJsonRequest.Builder<ArrayList<ConfigBean>>()
                .apiVer("100").typeKey("BY_Config_app")
                .requestListener(new XRequestListener<ArrayList<ConfigBean>>() {

                    @Override
                    public void onResponse(ArrayList<ConfigBean> bean) {
                        arConfig = bean;
                        for (ConfigBean configBean : bean) {
                            if (configBean.getName().equals("android_fuwu_version")) {
                                newConfigBean = configBean;
                                newVersion = Integer.parseInt(configBean.getValue().replace(".", ""));
                                break;
                            }
                        }

                        if (newVersion > version) {
                            hasNew.setVisibility(View.VISIBLE);
                        }
                    }

                }).errorListener(new XErrorListener() {

                    @Override
                    public void onErrorResponse(Exception exception, int code,
                                                String msg) {
                    }
                });

        MyJsonRequest<ArrayList<ConfigBean>> request = builder.build();
        HttpRequest.getDefaultRequestQueue().add(request);

    }

    UIAlertView02 delDialog;

    public void onManager(ConfigBean appUpdateBean) {
        delDialog = new UIAlertView02(this, appUpdateBean.getValue(), "有更新啦!", "以后再说", "立即更新");
        delDialog.show();

        delDialog.setClicklistener(new UIAlertView02.ClickListenerInterface() {

            public void doLeft() {
                delDialog.dismiss();
            }

            public void doRight() {
                String url = "";
                for (ConfigBean configBean : arConfig) {
                    if ("android_fuwu_url".equals(configBean.getName())) {
                        url = configBean.getValue();
                        break;
                    }
                }
                if (!url.equals("")) {
                    delDialog.dismiss();
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(uri);
                    startActivity(intent);
//                    Intent intent = new Intent(SttingActivity.this, WebActivity.class);
//                    intent.putExtra("url", url);
//                    startActivity(intent);
                } else {
                    Byalert.alert("下载地址有误");
                }
            }
        });
//        UpdateManager manager = new UpdateManager(this,
//                 "ceshi ",
//                "http://a.app.qq.com/o/simple.jsp?pkgname=com.itboye.sunsunhome","1.1.3");
//        manager.checkUpdateInfo();
    }


    BroadcastReceiver avartBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {

            insetINter();


            exitrela.setVisibility(View.VISIBLE);

        }

        ;
    };

    int version = 0;

    public void insetINter() {
        add_shap_title_tv.setText(R.string.activity_sttring);
        App app = (App) getApplication();
        obs = app.getSwitchLangObs();
        obser = new SwitchLanguageObserver(obs);

        try {
            PackageManager pm = App.ctx.getPackageManager();
            PackageInfo info = pm.getPackageInfo(App.ctx.getPackageName(), 0);
            String appVersion = info.versionName;
            versionname.setText(appVersion);
            version = Integer.parseInt(appVersion.replaceAll(".", ""));
        } catch (Exception e) {

        }

        resultData = (String) SPUtils.get(App.ctx, null,
                SPContants.PRODUCT_PHONE, "");
        tvtel.setText(resultData);
        tvtel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                showDialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {

            case R.id.protocalrela:
                Intent intent4 = new Intent(SttingActivity.this,
                        ProtocalActivity.class);
                startActivity(intent4);
                break;
            // case R.id.mylocationrelakefu:
            // LoginController.onReceiveClick(SttingActivity.this, null);
            // break;
            case R.id.aboutrela:

                Intent intent3 = new Intent(SttingActivity.this,
                        AboutActivity.class);
                startActivity(intent3);
                break;
            case R.id.mylocationrelalanguage:
                Intent intent = new Intent(SttingActivity.this,
                        LanguageActivity.class);
                startActivity(intent);
                break;
            case R.id.close_icon:
                finish();
                break;
            case R.id.mylocationrelaGeRen:
                LoginController.onPersonalsettingClick(SttingActivity.this, null);
                // Intent intent8 = new Intent();
                // intent8.setClass(App.ctx, PersonSettingActivity.class);
                // intent8.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                // startActivity(intent8);
                break;
            case R.id.exitrela:
                exit();
                break;
            case R.id.re_version:
                if (newVersion > version) {
                    onManager(newConfigBean);
                }else{
                    Byalert.alert("当前已经是最新版本!");
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (obs != null && obser != null)
            obs.deleteObserver(obser);
        super.onDestroy();
    }

    public void deleteInfo() {

        SharedPreferences sp = getSharedPreferences("share_by_data",
                MODE_PRIVATE);
        sp.edit().putString(SPContants.USER_ID, "")
                .putString(SPContants.MOBILE, "")
                .putString(SPContants.EMAIL, "").putString(SPContants.NICK, "")
                .putString(SPContants.PASSWORD, "")
                .putString(SPContants.AVATAR_URL, "")
                .putString(SPContants.USERNAME, "")
                .putString(SPContants.WX_Openid, "")
                .putString(SPContants.AQ_NUM, "")
                .putBoolean(SPContants.IS_LOGINED, false).commit();
    }

    public void exit() {

        try {
            PushAgent.getInstance(App.ctx)
                    .deleteAlias(
                            (String) SPUtils.get(App.ctx, null,
                                    SPContants.USER_ID, ""), "sunsun");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        deleteInfo();
        if (SPUtils.get(App.ctx, null, SPContants.LANGUAGE, "").equals(
                "chinese")) {
            LoginController.setLoginState(new UnLoginState());

            Intent intent = new Intent(SttingActivity.this,
                    MainHomeActivity.class);
            startActivity(intent);
            Intent intent1 = new Intent(EXITCHANGE);
            sendBroadcast(intent1);
            this.finish();
        } else if (SPUtils.get(App.ctx, null, SPContants.LANGUAGE, "").equals(
                "english")) {
            LoginController.setLoginState(new UnLoginState());

            Intent intent2 = new Intent(SttingActivity.this,
                    MainHomeEnglishActivity.class);
            startActivity(intent2);
            Intent intent12 = new Intent(EXITCHANGE);
            sendBroadcast(intent12);
            this.finish();

        }
    }

    private void showDialog() {
        // TODO Auto-generated method stub
        final AlertDialog alertDialog = new AlertDialog.Builder(
                SttingActivity.this).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.show_dilog);
        TextView tv_title = (TextView) window.findViewById(R.id.title);
        tv_title.setText("提示");
        TextView tv_message = (TextView) window.findViewById(R.id.message);
        tv_message.setText("是否拨打\t\t" + resultData);
        Button btn_save = (Button) window.findViewById(R.id.save);
        btn_save.setText("是");

        Button canButton = (Button) window.findViewById(R.id.cancel);
        btn_save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
                        + resultData));
                if (ActivityCompat.checkSelfPermission(SttingActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                startActivity(intent);
            }
        });
        canButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
            }
        });

    }
}
